<template>
    <div class="wrapper">
        <div id="x-spreadsheet-demo"></div>
        <Icon class="full_icon" name="el-icon-FullScreen" @click="onFullScreen" size="18" />
    </div>
</template>
<script setup>
import { onMounted, nextTick } from 'vue'
import Spreadsheet from "x-data-spreadsheet";
import 'x-data-spreadsheet/dist/locale/zh-cn';
import screenfull from 'screenfull'
Spreadsheet.locale('zh-cn');
const emit = defineEmits(['valueChange'])
const props = defineProps({
    value: {
        type: Array, default() {
            return []
        }
    },
})

const onFullScreen = () => {
    screenfull.toggle(document.getElementById('x-spreadsheet-demo'))
    screenfull.onchange(() => {
        state.isFullScreen = screenfull.isFullscreen
    })
}

onMounted(async () => {
    await nextTick()
    const getRow = (row) => {
        const arr = []
        for (let key in row.cells) {
            arr.push(
                row.cells[key].text
            )
        }
        return arr
    }
    const s = new Spreadsheet("#x-spreadsheet-demo", {
        showToolbar: false,
        showBottomBar: false
    })
        .loadData({}) // load data
        .change(data => {
            const newRows = []

            let row = null
            let column = getRow(data.rows[0])
            const l = Object.keys(data.rows).length - 1
            for (let i = 1; i < l; i++) {
                const item = {}
                row = getRow(data.rows[i])
                column.forEach((key, keyi) => {
                    item[key] = row[keyi]
                })
                newRows.push({
                    ...item
                })
            }
            emit('valueChange', newRows)
            // save data to db
        });

    // data validation
    s.validate()

    // 设置数据
    const tableData = props.value
    if (tableData.length > 0) {
        // 设置列标题
        const keys = Object.keys(tableData[0])
        for (let i = 0, l = keys.length; i < l; i++) {
            s.cellText(0, i, keys[i])
        }
        // 设置内容
        for (let i = 0, l = tableData.length; i < l; i++) {
            const item = tableData[i]
            for (let j = 0, l = keys.length; j < l; j++) {
                s.cellText(i + 1, j, item[keys[j]])
            }
        }

        s.reRender();
    }
})
</script>
<style lang="less" scoped>
.wrapper {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: auto;

    &:hover {
        .full_icon {
            animation: twinkle 0.3s ease-in-out;

            visibility: visible;
        }
    }

    .full_icon {
        position: absolute;
        bottom: 10px;
        right: 10px;
        cursor: pointer;
        visibility: hidden;
        z-index: 100;
    }
}
</style>
<style lang="less">
.x-spreadsheet-selector .x-spreadsheet-selector-corner,
.x-spreadsheet-selector .x-spreadsheet-selector-area {
    box-sizing: initial;
}
</style>